<?php
namespace yii\easyii\helpers;

use Yii;
use yii\helpers\Inflector;
use yii\helpers\StringHelper;

class Data
{
    public static function cache($key, $duration, $callable)
    {
        $cache = Yii::$app->cache;
        if($cache->exists($key)){
            $data = $cache->get($key);
        }
        else{
            $data = $callable();

            if($data) {
                $cache->set($key, $data, $duration);
            }
        }
        return $data;
    }

    public static function getLocale()
    {
        $locale = strtolower(substr(Yii::$app->language, 0, 2));
        return $locale == 'zh' ? Yii::$app->language : $locale;
    }

    public static function getMutiValue($model,$key){
        $strtext = $model[$key."_".strtolower(str_replace('-','_',Yii::$app->language))];
        return !empty($strtext) ? $strtext : $model[$key];
    }

    public static function setDefaultAttributes($model){
        $defaultLanguage = isset(Yii::$app->params['defaultLanguage']) ? Yii::$app->params['defaultLanguage'] : 'en-US';
        foreach ($model->behaviors()['multilingual']['attributes'] as $key) {
            $model[$key] = $model[$key.'_'.strtolower(str_replace('-','_',$defaultLanguage))];
        }
    }

    /**
    * Returns string with newline formatting converted into HTML paragraphs.
    *
    * @param string $string String to be formatted.
    * @param boolean $line_breaks When true, single-line line-breaks will be converted to HTML break tags.
    * @param boolean $xml When true, an XML self-closing tag will be applied to break tags (<br />).
    * @return string
    */
    public static function nl2p($string, $line_breaks = true, $xml = true)
    {
        // Remove existing HTML formatting to avoid double-wrapping things
        $string = str_replace(array('<p>', '</p>', '<br>', '<br />'), '', $string);
        // It is conceivable that people might still want single line-breaks
        // without breaking into a new paragraph.
        if ($line_breaks == true)
            return '<p>'.preg_replace(array("/([\n]{2,})/i", "/([^>])\n([^<])/i"), array("</p>\n<p>", '<br'.($xml == true ? ' /' : '').'>'), trim($string)).'</p>';
        else 
            return '<p>'.preg_replace("/([\n]{1,})/i", "</p>\n<p>", trim($string)).'</p>';
    }
}